package com.basker.pisces.core.meta.bean;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import com.basker.pisces.core.IDataContract;
import com.basker.pisces.core.IDataContractCollection;
import com.basker.pisces.core.enums.DataObjectState;

public class DataContractList<T> extends ArrayList<T> implements IDataContractCollection {

    private static final long serialVersionUID = -6551236669265023681L;

    private List<IDataContract> removedObjects;

    @Override
    public void clear() {
        for (T o : this) {
            this.addRemovedObject(o);
        }
        super.clear();
    }

    @Override
    public List<IDataContract> getRemovedObjects() {
        return removedObjects;
    }

    @Override
    public T remove(int index) {
        if (index >= 0 && index < this.size()) {
            this.addRemovedObject(this.get(index));
            return super.remove(index);
        }

        return null;
    }

    @Override
    public boolean remove(Object o) {
        this.addRemovedObject(o);
        return super.remove(o);
    }

    @Override
    public boolean removeAll(Collection<?> c) {
        for (Object o : c) {
            this.addRemovedObject(o);
        }

        return super.removeAll(c);
    }

    private void addRemovedObject(Object o) {
        if (!(o instanceof IDataContract)) {
            return;
        }

        IDataContract dataContract = (IDataContract) o;
        if (dataContract.isFromDB()) {
            dataContract.setState(DataObjectState.Deleted);

            if (this.removedObjects == null) {
                this.removedObjects = new ArrayList<>();
            }

            this.removedObjects.add(dataContract);
        } else {
            dataContract.setState(DataObjectState.Detached);
        }

    }

}
